package com.cetcs.kmga.dataManager.global;

import com.cetcs.kmga.dataManager.dao.hbase.LogPage;
import com.cetcs.kmga.dataManager.util.DruidH2Pool;
import com.cetcs.kmga.dataManager.util.EhcacheUtil;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.TimerTask;

/**
 * 日志缓存清理线程
 * 作用是清理一段时间未响应的查询结果
 *
 * @author xutao
 * @version V1.0 创建时间：2017-11-30 14:09
 *          Copyright 2017 by CETC
 */
public class LogQueryEhcacheTimerTask extends TimerTask {
    private final static Logger LOGGER = LoggerFactory.getLogger(LogQueryEhcacheTimerTask.class);

    /**
     * 默认清理的时间是30分钟
     */
    private long timePir = 1000 * 60 * 30;

    @Override
    public void run() {
        //扫描缓存中是否有节点
        EhcacheUtil ehcacheUtil = new EhcacheUtil(DataManagerConstants.LOG_QUERY_CACHE_CODE);
        Map<Object, Element> allElements = ehcacheUtil.getAllElements( );
        Date currentTime = new Date( );
        LOGGER.info("===================timer removes task init !=============================");
        if (allElements != null && !allElements.isEmpty( )) {
            allElements.forEach((k, v) -> {
                try {
                    LogPage ret = (LogPage) v.getObjectValue( );
                    Date queryTime = ret.getQueryTime( );
                    long minus = currentTime.getTime( ) - queryTime.getTime( );
                    //如果时间大于30分钟则需要将缓存的数据销毁，释放内存
                    //需要删除H2内存库中的数据，以及删除Ehcache中缓存的数据
                    if (minus > timePir) {
                        ehcacheUtil.remove(String.valueOf(k));
                        DruidH2Pool.getInstance( ).remvoeCacheTb(LogQueryEhcacheOper.makeH2TbNameByUserId(ret.getQueryUserId( )));
                    }
                } catch (Exception ex) {
                    LOGGER.error("timer removes log cache error,error msg is:" + ex.getMessage( ));
                }
            });
        }
    }

    public void setTimePir(long timePir) {
        this.timePir = timePir;
    }
}
